<template>
  <div
    :class="[
      'flexBox',
      { comBox: isEdit },
      { pointed: tempComData.focus && isEdit },
    ]"
    @drop.stop="handComDrop"
    @dragover="dragover"
  >
    {{ tempComData.comPorps.content }}
    <div
      class="addBtn"
      v-if="tempComData.focus && isEdit"
      @click="addChildFlexBox"
    >
      <img :src="require('@/' + 'assets/add-btn.png')" draggable="false" />
    </div>
    <template v-if="tempComData.children && tempComData.children.length != 0">
      <component
        v-for="item in tempComData.children"
        :class="{ pointed: item.focus && isEdit }"
        :is="item.comName"
        :is-edit="isEdit"
        :key="item.id"
        :com-data="item"
        :style="item.style"
        :draggable="!item.children"
        :id="item.id"
        @click="onChildPointed($event, item, tempComData)"
        @dragenter="onDragEnter($event, item, tempComData)"
        @dragstart.stop="dragStart($event, item, tempComData)"
      />
    </template>
  </div>
</template>

<script setup>
import { computed, toRefs, defineProps } from "vue";
import { useStore } from "vuex";

const porps = defineProps({
  comData: {
    type: Object,
    required: true,
  },
  isEdit: {
    type: Boolean,
    required: true,
  },
});
const emit = defineEmits(["update:comData", "addFlexBox"]);
const { comData, isEdit } = toRefs(porps);

const tempComData = computed({
  get: () => comData.value,
  set: (val) => {
    emit("update:comData", val);
  },
});

const store = useStore();
//点击子组件
const onChildPointed = (e, comData, childWraper) => {
  if (isEdit.value) {
    console.log(isEdit.value);
    e.preventDefault();
    e.stopPropagation();
    store.dispatch("setSelectedCom", { comData, childWraper });
  }
};
const addChildFlexBox = () => {
  store.dispatch("addChildFlexBox");
};
const onDragEnter = (e, comData, childWraper) => {
  //拖动到弹性盒子进行事件拦截，非弹性盒子冒泡
  if (comData.comName === "FlexBox") {
    onChildPointed(e, comData, childWraper);
  }
};
const handComDrop = (event) => {
  const { offsetY, offsetX } = event;
  store.dispatch("dropCom2FlexBox", { offsetY, offsetX });
};
const dragover = (e) => {
  e.preventDefault();
};
const dragStart = (e, dragedCom, childWraper) => {
  const { offsetY, offsetX } = e;
  store.commit("setDragedComInfo", {
    offsetY,
    offsetX,
    dragedCom,
    childWraper,
  });
};
</script>

<style lang="less" scoped>
.comBox {
  outline: 1px dashed #409eff;
  outline-offset: -3px;
  cursor: pointer;
}

.flexBox {
  position: relative;
  display: flex;
  width: 100%;
  height: 60px;
  flex-direction: row;
  box-sizing: border-box;
  overflow: hidden;

  .addBtn {
    position: absolute;
    top: calc(50% - 8px);
    left: calc(50% - 8px);
    z-index: 9;

    img {
      cursor: pointer;
      width: 16px;
      height: 16px;
    }
  }
}

.pointed {
  outline: 2px solid #409eff;
  outline-offset: -4px;
  background-color: rgba(178, 190, 195, 0.2);
}
</style>
